package com.mlnx.work.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mlnx.common.entity.Response;
import com.mlnx.common.form.PageForm;
import com.mlnx.work.entity.ProjectDir;
import com.mlnx.work.entity.ProjectTask;
import com.mlnx.work.pojo.dto.DateDTO;
import com.mlnx.work.pojo.vo.*;
import com.mlnx.work.service.ProjectDirService;
import com.mlnx.work.service.ProjectTaskService;
import com.mlnx.work.service.StatisticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.shan.spring.base.BaseController;
import org.shan.spring.base.annotations.SysLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.mlnx.work.enums.ProjectStatusEnum.DONE;
import static com.mlnx.work.enums.ProjectStatusEnum.OVERDUE;

/**
 * @Author: Akrio
 * @Date: 2021-01-19 8:47
 */
@SysLog(title = "任务统计")
@Api(value = "统计接口", tags = {"统计接口"})
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {

    @Autowired
    private ProjectTaskService projectTaskService;
    @Autowired
    private ProjectDirService projectDirService;
    @Autowired
    private StatisticsService statisticsService;

    @ApiOperation("获取企业任务统计")
    @GetMapping("/enterpriseTask")
    public Response enterpriseTask() {
        EnterpriseTaskStatisticsVO etv = new EnterpriseTaskStatisticsVO();
        Map<String, Object> map = new HashMap<>();
        map.put("parent_id", 0);
        map.put("status", OVERDUE);
        //任务完成率
        int count = projectTaskService.count(new QueryWrapper<ProjectTask>().eq("status", DONE));//已完成任务总数
        int size = projectTaskService.count();
        etv.setCompleteness(String.format("%.1f", NumberUtil.div(count, size) * 100));//任务总数
        etv.setDelayRate(String.format("%.1f", NumberUtil.div(
                projectDirService.count(new QueryWrapper<ProjectDir>().allEq(map)),//逾期项目
                projectDirService.count(new QueryWrapper<ProjectDir>().eq("parent_id", 0))) * 100));//总项目数
        etv.setDelay(projectTaskService.count(new QueryWrapper<ProjectTask>().eq("status", OVERDUE)));//逾期任务
        etv.setFinished(count);//已完成
        etv.setTaskSum(size);
        return result(etv);
    }
//    @ApiOperation("获取企业每日新增和完成任务趋势图")
//    @GetMapping("/dailyTrend2")
//    public Response dailyTrend2(DateDTO dateDTO){
//        if(dateDTO.getEndTime()==null)
//            dateDTO.setEndTime(new Date().getTime());
//        List<DailyTrendVO> dailyTrendVOS = new ArrayList<>();
//        List<ProjectTask> tasks = projectTaskService.list(new QueryWrapper<ProjectTask>().gt("create_time", dateDTO.getStartTime()));//获取所有该时间创建之前的任务
//        long start = dateDTO.getStartTime() + (1000 * 60 * 60 * 24);//加一天
//        while (dateDTO.getEndTime()>=dateDTO.getStartTime()){
//
//            for (ProjectTask task:tasks){
//                int i = 0;
//                if(dateDTO.getStartTime() < task.getCreateTime()&&task.getCreateTime() < start){
//                    i++;
//                }
//            }
//            dateDTO.setStartTime(start);
//        }
//        return result(dailyTrendVOS);
//    }


    @ApiOperation("获取企业每日新增和完成任务趋势图")
    @GetMapping("/dailyTrend")
    public Response dailyTrend(DateDTO dateDTO) {
        if (dateDTO.getStartTime() == null)
            dateDTO.setStartTime(new Date().getTime() - (1000 * 60 * 60 * 24 * 7));//提前7天查询

        if (dateDTO.getEndTime() == null)
            dateDTO.setEndTime(new Date().getTime());
        List<ProjectTask> tasks = projectTaskService.list(new QueryWrapper<ProjectTask>().gt("create_time", dateDTO.getStartTime()));//获取选定时间后的所有任务
        List<DailyTrendVO> dailyTrendVOS = new ArrayList<>();
        while (dateDTO.getEndTime() >= dateDTO.getStartTime()) {
            int add = 0, finish = 0;
            DailyTrendVO dailyTrendVO = new DailyTrendVO();
            long start = dateDTO.getStartTime() + (1000 * 60 * 60 * 24);
            for (ProjectTask task : tasks) {
                if (dateDTO.getStartTime() <= task.getCreateTime() && task.getCreateTime() <= start)//如果在这一天创建
                    add++;
                if (dateDTO.getStartTime() <= task.getCompletedTime() && task.getCompletedTime() <= start)//在这一天完成
                    finish++;
            }
            dailyTrendVO.setDate(dateDTO.getStartTime());
            dailyTrendVO.setNewTask(add);
            dailyTrendVO.setFinishTask(finish);
            dailyTrendVOS.add(dailyTrendVO);
            dateDTO.setStartTime(start);//每次加一天
        }

//        while (dateDTO.getEndTime() >= dateDTO.getStartTime()) {
//            DailyTrendVO dailyTrendVO = new DailyTrendVO();
//            dailyTrendVO.setDate(dateDTO.getStartTime());
//            long start = dateDTO.getStartTime() + (1000 * 60 * 60 * 24);
//            int createTask = projectTaskService.count(new QueryWrapper<ProjectTask>().between("create_time", dateDTO.getStartTime(), start));
//            int finishTask = projectTaskService.count(new QueryWrapper<ProjectTask>().between("origin_end_time", dateDTO.getStartTime(), start));
//            dailyTrendVO.setFinishTask(finishTask);
//            dailyTrendVO.setNewTask(createTask);
//            dailyTrendVOS.add(dailyTrendVO);
//            dateDTO.setStartTime(start);
//        }
        return result(dailyTrendVOS);
    }


//    @ApiOperation("获取企业每日新增和完成任务趋势图")
//    @GetMapping("/dailyTrend")
//    public Response dailyTrend(DateDTO dateDTO) {
//        long t = 3456000000L;
//        if ((new Date().getTime() - dateDTO.getStartTime()) > t)
//            return result("时间过长");
//        if (dateDTO.getEndTime() == null)
//            dateDTO.setEndTime(new Date().getTime());
//        List<DailyTrendVO> dailyTrendVOS = new ArrayList<>();
//        while (dateDTO.getEndTime() >= dateDTO.getStartTime()) {
//            DailyTrendVO dailyTrendVO = new DailyTrendVO();
//            dailyTrendVO.setDate(dateDTO.getStartTime());
//            long start = dateDTO.getStartTime() + (1000 * 60 * 60 * 24);
//            int createTask = projectTaskService.count(new QueryWrapper<ProjectTask>().between("create_time", dateDTO.getStartTime(), start));
//            int finishTask = projectTaskService.count(new QueryWrapper<ProjectTask>().between("origin_end_time", dateDTO.getStartTime(), start));
//            dailyTrendVO.setFinishTask(finishTask);
//            dailyTrendVO.setNewTask(createTask);
//            dailyTrendVOS.add(dailyTrendVO);
//            dateDTO.setStartTime(start);
//        }
//        return result(dailyTrendVOS);
//    }


    @ApiOperation("获取项目进度统计")
    @GetMapping("/projectSchedule")
    public Response projectSchedule(PageForm page) {
        Page<ProjectScheduleStatisticsVO> projectScheduleStatisticsVOPage = statisticsService.selectProject(page);
        List<ProjectTask> tasks = projectTaskService.list();//获取项目下所有任务
        List<ProjectDir> dirs = projectDirService.list();//获取项目下所有子项目
        List<ProjectScheduleStatisticsVO> pssList = projectScheduleStatisticsVOPage.getRecords();
        for (ProjectScheduleStatisticsVO pssv : pssList) {
            int unFinished = 0, delayTask = 0, finished = 0, allTask = 0;//计数器
            for (ProjectTask task : tasks) {
                if (task.getDirId() == pssv.getDirId()) {//属于该项目
                    allTask++;
                    switch (task.getStatus()) {
                        case DONE:
                            finished++;
                            break;
                        case OVERDUE:
                            delayTask++;
                            unFinished++;
                            break;
                        default:
                            unFinished++;
                            break;
                    }
                }
            }
            for (ProjectDir dir : dirs) {
                if (dir.getParentId() == pssv.getDirId()) {//属于该项目
                    allTask++;
                    switch (dir.getStatus()) {
                        case DONE:
                            finished++;
                            break;
                        case OVERDUE:
                            delayTask++;
                            unFinished++;
                            break;
                        default:
                            unFinished++;
                            break;
                    }
                }
            }
            pssv.setFinished(finished);
            pssv.setUnFinished(unFinished);
            pssv.setDelayTask(delayTask);
            if (allTask == 0) {
                pssv.setProjectSchedule("0");
            } else {
                pssv.setProjectSchedule(String.format("%.1f", NumberUtil.div(finished, allTask) * 100));
            }
        }
        return result(projectScheduleStatisticsVOPage);
    }

    @ApiOperation("获取成员进度统计")
    @GetMapping("/memberSchedule")
    public Response memberSchedule(PageForm pageForm) {

        Page<MemberScheduleStatisticsVO> memberScheduleStatisticsVOPage = statisticsService.selectMember(pageForm);
        List<MemberScheduleStatisticsVO> members = memberScheduleStatisticsVOPage.getRecords();//获取所有成员
        List<ProjectTask> tasks = projectTaskService.list();//所有任务
        List<ProjectDir> dirs = projectDirService.list();//所有项目
        for (MemberScheduleStatisticsVO member : members) {
            int unFinished = 0, delayTask = 0, finished = 0, taskNum = 0;
            for (ProjectTask task : tasks) {
                if (task.getManagerId() == member.getId()) {
                    taskNum++;
                }
            }
            for (ProjectDir dir : dirs) {
                if (dir.getManagerId() == member.getId()) {
                    switch (dir.getStatus()) {
                        case DONE:
                            finished++;
                            break;
                        case OVERDUE:
                            delayTask++;
                            unFinished++;
                            break;
                        default:
                            unFinished++;
                            break;
                    }
                }
            }
            member.setTaskSum(taskNum);
            member.setFinish(finished);
            member.setDelay(delayTask);
            member.setUnfinish(unFinished);
            if (member.getProjectSum() == null || member.getProjectSum() == 0) {
                member.setProjectSum(0);
                member.setDelayRate("0");
                member.setCompleteness("0");
            } else {
                member.setDelayRate(String.format("%.1f", NumberUtil.div(delayTask, (int) member.getProjectSum()) * 100));
                member.setCompleteness(String.format("%.1f", NumberUtil.div(finished, (int) member.getProjectSum()) * 100));
            }

        }
        return result(memberScheduleStatisticsVOPage);
    }

    //
//    @ApiOperation("获取项目进度统计")
//    @GetMapping("/projectSchedule")
//    public Response projectSchedule() {
//        List<ProjectScheduleStatisticsVO> pssList = statisticsService.selectProject();
//        for (ProjectScheduleStatisticsVO pssv : pssList) {
//            List<ProjectTask> tasks = projectTaskService.list(new QueryWrapper<ProjectTask>().eq("dir_id", pssv.getDirId()));//获取项目下所有任务
//            List<ProjectDir> dirs = projectDirService.list(new QueryWrapper<ProjectDir>().eq("parent_id", pssv.getDirId()));//获取项目下所有子项目
//            int unFinished = 0, delayTask = 0, finished = 0;//计数器
//            for (ProjectTask task : tasks) {
//                switch (task.getStatus()) {
//                    case DONE:
//                        finished++;
//                        break;
//                    case OVERDUE:
//                        delayTask++;
//                        unFinished++;
//                        break;
//                    default:
//                        unFinished++;
//                        break;
//                }
//            }
//            for (ProjectDir dir : dirs) {
//                switch (dir.getStatus()) {
//                    case DONE:
//                        finished++;
//                        break;
//                    case OVERDUE:
//                        delayTask++;
//                        unFinished++;
//                        break;
//                    default:
//                        unFinished++;
//                        break;
//                }
//            }
//            pssv.setFinished(finished);
//            pssv.setUnFinished(unFinished);
//            pssv.setDelayTask(delayTask);
//            int sum = tasks.size() + dirs.size();
//            if (sum == 0) {
//                pssv.setProjectSchedule("该项目下无任务");
//            } else {
//                pssv.setProjectSchedule(String.format("%.1f", NumberUtil.div(finished, sum) * 100));
//            }
//        }
//        return result(pssList);
//    }


//    @ApiOperation("获取项目进度统计")
//    @GetMapping("/projectSchedule")
//    public Response projectSchedule(){
//        List<ProjectScheduleStatisticsVO> pssList = statisticsService.selectProject();
//        for(ProjectScheduleStatisticsVO pssv : pssList){
//            int unFinished = 0,delayTask = 0,finished = 0;//计数器
//            List<ProjectTask> projectTasks = recursionCount(pssv.getDirId(), new ArrayList<ProjectTask>());//返回该目录下所有任务
//            for(ProjectTask projectTask : projectTasks){
//                if(projectTask.getStatus()==TaskStatusEnum.DONE){//已完成
//                    finished++;
//                }else{//未完成
//                    if(projectTask.getStatus()==TaskStatusEnum.OVERDUE){//逾期任务
//                        delayTask++;
//                    }
//                    unFinished++;
//                }
//            }
//            pssv.setFinished(finished);
//            pssv.setUnFinished(unFinished);
//            pssv.setDelayTask(delayTask);
//            if(projectTasks.size()==0){
//                pssv.setProjectSchedule("该项目下无任务");
//            }else {
//                pssv.setProjectSchedule(String.format("%.1f", NumberUtil.div(finished,projectTasks.size())*100));
//            }
//        }
//        return result(pssList);
//    }

    //获取某个项目下所有任务
    private List<ProjectTask> recursionCount(int id, List<ProjectTask> projectTasks) {
        projectTasks.addAll(projectTaskService.list(new QueryWrapper<ProjectTask>().eq("dir_id", id))); //获取该目录下所有任务
        List<ProjectDir> list = projectDirService.list(new QueryWrapper<ProjectDir>().eq("parent_id", id));//获取该目录下所有目录
        if (list.size() > 0) {//存在目录
            for (ProjectDir pd : list) {
                recursionCount(pd.getId(), projectTasks);
            }
        }
        return projectTasks;
    }


}



















